package leetcode.剑指offer.前40;

import leetcode.剑指offer.pojo.Node;
import org.junit.Test;

import java.util.HashMap;

/**
 * @author :songyaozhang
 * @date :Created 2021/7/30 11:39
 * @description :
 */
public class 剑指_35_复杂链表的复制 {
    @Test
    public void test() {
        Solution solution = new Solution();

    }

    class Node {
        int val;
        Node next;
        Node random;

        public Node(int val) {
            this.val = val;
            this.next = null;
            this.random = null;
        }
    }

    /*class Solution {
        public Node copyRandomList(Node head) {
            if (head == null) return null;
            HashMap<Node, Node> map = new HashMap<>();
            Node temp = head;
            while (temp != null) {
                map.put(temp, new Node(temp.val));
                temp = temp.next;
            }
            temp = head;
            while (temp != null) {
                map.get(temp).next = map.get(temp.next);
                map.get(temp).random = map.get(temp.random);
                temp = temp.next;
            }
            return map.get(head);
        }
    }*/

    /*
// Definition for a Node.
class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}
*/
    class Solution {
        public Node copyRandomList(Node head) {
            if (head == null) return null;
            Node cur = head;
            //复制链表
            while (cur != null) {
                Node temp = new Node(cur.val);
                temp.next = cur.next;
                cur.next = temp;
                cur = temp.next;
            }
            //处理随机指针
            cur = head;
            while (cur != null) {
                if (cur.random != null) {
                    cur.next.random = cur.random.next;
                }
                cur = cur.next.next;
            }
            //拆分链表
            cur = head.next;
            Node pre = head, res = head.next;
            while(cur.next != null) {
                pre.next = pre.next.next;
                cur.next = cur.next.next;
                pre = pre.next;
                cur = cur.next;
            }
            pre.next = null; // 单独处理原链表尾节点
            return res;      // 返回新链表头节点
        }
    }

}
